package cn.yh.register.hosp.service.impl;

import cn.yh.register.common.exception.RegisterException;
import cn.yh.register.common.result.ResultCodeEnum;
import cn.yh.register.hosp.repository.ScheduleRepository;
import cn.yh.register.hosp.service.DepartmentService;
import cn.yh.register.hosp.service.HospitalService;
import cn.yh.register.hosp.service.ScheduleService;
import cn.yh.register.model.hosp.BookingRule;
import cn.yh.register.model.hosp.Department;
import cn.yh.register.model.hosp.Hospital;
import cn.yh.register.model.hosp.Schedule;
import cn.yh.register.vo.hosp.BookingScheduleRuleVo;
import cn.yh.register.vo.hosp.ScheduleOrderVo;
import cn.yh.register.vo.hosp.ScheduleQueryVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.internal.DeepDifference;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    ScheduleRepository scheduleRepository;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    HospitalService hospitalService;
    @Autowired
    DepartmentService departmentService;

    @Override
    public void save(Map<String, Object> objectMap) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(objectMap), Schedule.class);
        Schedule sche = scheduleRepository.getSchedulesByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if (sche == null) {
            // 没有 新增
            schedule.setCreateTime(new Date());
            schedule.setIsDeleted(0);
        } else {
            // 有 修改
            schedule.setId(sche.getId());
            schedule.setCreateTime(sche.getCreateTime());
            schedule.setIsDeleted(sche.getIsDeleted());
        }
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);

    }

    @Override
    public Page<Schedule> selectPage(Integer current, Integer limit, ScheduleQueryVo scheduleQueryVo) {
        Schedule schedule = new Schedule();
        schedule.setIsDeleted(0);
        BeanUtils.copyProperties(scheduleQueryVo, schedule);

        //创建分页条件
        PageRequest pageRequest = PageRequest
                .of(current - 1, limit, Sort.by(Sort.Direction.DESC, "createTime"));


        //创建查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)  //构建对象
                .withIgnoreCase(true);//改变默认大小写忽略方式；忽略大小写

        //创建实例
        Example<Schedule> example = Example.of(schedule, matcher);
        return scheduleRepository.findAll(example, pageRequest);
    }

    /**
     * 删除排班信息
     *
     * @param hoscode       医院编号
     * @param hosScheduleId 排班编号（医院自己的排班主键）
     */
    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getSchedulesByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        schedule.setIsDeleted(1);
        scheduleRepository.save(schedule);
    }

    /**
     * 按日期获取排班数据
     *
     * @param current 当前页
     * @param limit   每页条数
     * @param hoscode 医院编号
     * @param depcode 科室编号
     * @return Map<String, Object>  排班日期分页数据
     */
    @Override
    public Map<String, Object> getRuleSchedule(Integer current, Integer limit, String hoscode, String depcode) {
        // 查询条件 : hoscode,depcode
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode);
        //定义聚合操作
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")  // 按排班日期分组
                        .first("workDate").as("workDate")//分组后每组的第一条数据的排班日期起别名叫workDate
                        .count().as("docCount")  //分组后这一组的排班数量作为医生数量
                        .sum("reservedNumber").as("reservedNumber") // 分组后每组的可预约数加起来就是当天总的可预约数
                        .sum("availableNumber").as("availableNumber"),//分组后每组的剩余预约数加起来就是当天总的剩余预约数
                Aggregation.sort(Sort.Direction.DESC, "workDate"),//按照日期降序
                Aggregation.skip((current - 1) * limit), //分页
                Aggregation.limit(limit)
        );
        //执行聚合操作
        AggregationResults<BookingScheduleRuleVo> aggResults = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        //取出列表数据
        List<BookingScheduleRuleVo> bookingScheduleRuleVos = aggResults.getMappedResults();
        //遍历列表   设置周几
        for (BookingScheduleRuleVo ruleVo : bookingScheduleRuleVos) {
            String dayOfWeek = this.getDayOfWeek(new DateTime(ruleVo.getWorkDate()));
            ruleVo.setDayOfWeek(dayOfWeek);
        }

        //定义聚合操作  按日期分组  统计总组数
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")  // 按排班日期分组
        );

        //执行聚合操作  得到总组数
        int total = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class).getMappedResults().size();

        //组装数据返回
        Map<String, Object> result = new HashMap<>();

        //获取医院名称
        String hosName = hospitalService.getByHoscode(hoscode).getHosname();
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);
        result.put("bookingScheduleRuleList", bookingScheduleRuleVos);
        result.put("total", total);
        result.put("baseMap", baseMap);

        return result;
    }

    /**
     * 查询某天的排版信息
     *
     * @param hoscode  医院编号
     * @param depcode  科室编号
     * @param workDate 日期
     * @return List<Schedule>
     */
    @Override
    public List<Schedule> getScheduleList(String hoscode, String depcode, String workDate) {
        List<Schedule> scheduleList = scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());
        return scheduleList;
    }

    /**
     * 获取排班可预约日期数据
     *
     * @param current 当前页码
     * @param limit   每页条数
     * @param hoscode 医院code
     * @param depcode 科室code
     * @return
     */
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer current, Integer limit, String hoscode, String depcode) {
        //医院对象
        Hospital hospital = hospitalService.getByHoscode(hoscode);

        //预约规则
        BookingRule bookingRule = hospital.getBookingRule();

        // TODO 根据预约规则计算可预约的日期规则
        IPage<Date> dateIPage = this.getDateList(current, limit, bookingRule);

        //日期列表
        List<Date> dateList = dateIPage.getRecords();

        //排班数据查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);

        //定义聚合操作，获取课预约的排版数据
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria), // 匹配查询条件
                Aggregation.group("workDate")//按workDate分组
                        .first("workDate").as("workDate")  //分组后第一条数据的workDate起别名叫workDate
                        .count().as("docCount")  //分组后这一组的数量作为医生的数量
                        .sum("reservedNumber").as("reservedNumber") // 分组后这一组的reservedNumber加起来就是总的预约数
                        .sum("availableNumber").as("availableNumber") // availableNumber  总的剩余预约数

        );
        //执行聚合操作
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);

        //  取出聚合操作后列表数据
        List<BookingScheduleRuleVo> scheduleRuleVoList = aggregationResults.getMappedResults();

        //为方便操作将list转为map   key：排版日期   value：排版数据（BookingScheduleRuleVo）
        Map<Date, BookingScheduleRuleVo> map = scheduleRuleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate,
                BookingScheduleRuleVo -> BookingScheduleRuleVo));
        //组装排版数据
        List<BookingScheduleRuleVo> voList = new ArrayList<>();
        for (int i = 0; i < dateList.size(); i++) {
            Date date = dateList.get(i);
            //拿日期列表中的每一个日期作为key，去maap中找value
            BookingScheduleRuleVo ruleVo = map.get(date);
            if (ruleVo == null) {
                //这天没有排班
                ruleVo = new BookingScheduleRuleVo();
                ruleVo.setDocCount(0);
                ruleVo.setAvailableNumber(-1);
                ruleVo.setStatus(-1); // -1:当天已停止挂号
            } else {
                //有排班，不同的情况设置不同状态
                // 最后一页的最后一条数据显示即将放号
                if (current == dateIPage.getPages() && i == dateList.size() - 1) {
                    ruleVo.setStatus(1);  // 1 即将放号
                } else {
                    ruleVo.setStatus(0); // 0 正常
                }
                //当天的停挂时间
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                //第一页的第一条数据
                if (current == 1 && i == 0) {
                    //如果当前已经过了停号时间，则不能预约
                    if (stopTime.isBeforeNow()) {
                        ruleVo.setStatus(-1); // 当天已停止挂号
                    }

                }


            }
            //设置日期 & 周几
            ruleVo.setWorkDateMd(ruleVo.getWorkDate());
            ruleVo.setDayOfWeek(this.getDayOfWeek(new DateTime(ruleVo.getWorkDate())));
            voList.add(ruleVo);
        }
        Map<String, Object> result = new HashMap<>();

        // 其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        // 医院名称
        baseMap.put("hosname", hospitalService.getByHoscode(hoscode).getHosname());
        // 科室
        Department department = departmentService.getDepartment(hoscode, depcode);
        // 大科室名称
        baseMap.put("bigname", department.getBigname());
        // 科室名称
        baseMap.put("depname", department.getDepname());
        // 日期 年月日
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        // 放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        // 停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        // 可预约的排班数据
        result.put("bookingScheduleList", voList);
        // 日期列表总记录数
        result.put("total", dateIPage.getTotal());
        //基础数据
        result.put("baseMap", baseMap);
        return result;
    }

    /**
     * 查看排版详情
     *
     * @param scheduleId 排班id
     * @return 排版详情
     */
    @Override
    public Schedule getById(String scheduleId) {
        Optional<Schedule> optional = scheduleRepository.findById(scheduleId);
        if (optional.isPresent()) {
            Schedule schedule = optional.get();
            return this.packSchedule(schedule);
        }
        return null;
    }

    /**
     * 获取下单需要的排版数据
     * @param scheduleId 排班id
     * @return 下单需要的排版数据
     */
    @Override
    public ScheduleOrderVo getScheduleOrder(String scheduleId) {
        Schedule schedule = this.getById(scheduleId);
        if (schedule == null) {
            throw new RegisterException(ResultCodeEnum.PARAM_ERROR);
        }
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        BeanUtils.copyProperties(schedule,scheduleOrderVo);
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        //医院名称
        scheduleOrderVo.setHosname(hospital.getHosname());
        //科室名称
        scheduleOrderVo.setDepname(departmentService.getDepartment(schedule.getHoscode(),schedule.getDepcode()).getDepname());
        //安排日期
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        //安排时间
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        //退号时间
        BookingRule bookingRule = hospital.getBookingRule();
        Date quitDate = new DateTime(schedule.getWorkDate()).plusDays(bookingRule.getQuitDay()).toDate();
        DateTime quitTime = this.getDateTime(quitDate, bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());
        //挂号开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        //挂号结束时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());
        //当天停挂时间

        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());


        return scheduleOrderVo;
    }

    /**
     * 更新排班
     * @param schedule 排班对象
     */
    @Override
    public void updateSchedule(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
        log.info("【医院服务-更新号源】：{}", JSONObject.toJSONString(schedule));
    }

    /**
     * 根据医院的排班主键查询排班
     * @param hosScheduleId 排班主键
     * @return 排版对象
     */
    @Override
    public Schedule getByHosScheduleId(String hosScheduleId) {
        return scheduleRepository.findByHosScheduleId(hosScheduleId);
    }

    // 处理排班对象
    private Schedule packSchedule(Schedule schedule){
        // hosname
        String hosname = hospitalService.getByHoscode(schedule.getHoscode()).getHosname();
        // depname
        String depname = departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode()).getDepname();
        // dayOfWeek
        String dayOfWeek = this.getDayOfWeek(new DateTime(schedule.getWorkDate()));
        schedule.getParam().put("hosname", hosname);
        schedule.getParam().put("depname", depname);
        schedule.getParam().put("dayOfWeek", dayOfWeek);
        return schedule;
    }

    //根据预约规则计算可预约的日期列表
    private IPage<Date> getDateList(Integer current, Integer limit, BookingRule bookingRule) {

        //预约周期
        Integer cycle = bookingRule.getCycle();
        //当天的放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //如果当前时间大鱼当天的放号时间，则预约周期+1，最后一天显示即将放号
        if (releaseTime.isBeforeNow()) {
            cycle += 1;
        }
        //根据预约周期计算日期列表
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            //计算后面的每一天
            String dateStr = new DateTime().plusDays(i).toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateStr).toDate());
        }
        //对日期列表做分页
        int start = (current - 1) * limit;
        int end = start + limit;
        if (end >= dateList.size()) {
            end = dateList.size();
        }
        //当前页的列表数据
        List<Date> currentList = new ArrayList<>();
        for (int i = start; i < end; i++) {
            currentList.add(dateList.get(i));
        }
        //组装分页数据到page对象中
        IPage<Date> dateIPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, 7, dateList.size());
        //装入当前页的列表数据
        dateIPage.setRecords(currentList);

        return dateIPage;
    }

    /**
     * 将String类型的时间（格式：HH:mm）转换为DateTime类型（格式：yyyy-MM-dd HH:mm）
     *
     * @param date    日期（年月日）
     * @param timeStr 时间字符串（时分）
     * @return 年月日时分（yyyy-MM-dd HH:mm）
     */
    private DateTime getDateTime(Date date, String timeStr) {
        String dateStr = new DateTime(date).toString("yyyy-MM-dd");
        return DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateStr + " " + timeStr);
    }

    //根据日期返回周几
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }
}
